//
//  SEGOrderInputDetailViewController.m
//  Uhomebk
//
//  Created by 梁昆 on 2017/7/12.
//  Copyright © 2017年 com.segi. All rights reserved.
//

//封装起来最后的详情页面
#import "SEGOrderInputDetailViewController.h"
#import "ControlTemplateViewController.h"
#import "SEGOrderInputHttpManager.h"
#import "SEGInputTypeView.h"
#import <AVFoundation/AVFoundation.h>
#import "SEGBasicBussinessCommonDefine.h"

@interface SEGOrderInputDetailViewController ()<
ControlTemplateViewControllerDelegate,
SEGInputTypeViewDelegate,UIScrollViewDelegate
>{
    UIScrollView *aScrollView;  //底部ScrollView
//    UIView *controlsBox; // 工单控件容器
    ControlTemplateViewController *controlVC; //模板控件
    CGFloat nowY;
    NSMutableArray *dataArray;  //存储传入控件的参数
    NSArray *titleArray;    //存储
    NSMutableDictionary *dictReception; //存储前一个控制器传入的item字典数据
    
    NSString *busiTypeId;//服务类型id
    NSString *busiTypeName;//服务类型名字
    NSString *bespeakDate;//预约时间
    NSString *bespeakTimes;//预约时间段
    NSString *bespeakEnd;//预约时间段结束时间戳
    NSString *radioHouseId;//房屋控件的attrInstId
}
@property (nonatomic, strong)SEGOrderInputHttpManager *orderInputManager; // 工单录入网络请求Manager
/**
 是否正在提交
 */
@property (nonatomic, assign) BOOL isSubmit;

@end

@implementation SEGOrderInputDetailViewController
    
- (void)setupUI {
    [self showCustomNavigationBackButton];
    
    //提交
    UIButton* submit = [UIButton buttonWithType:UIButtonTypeCustom];
    [submit setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
    [submit setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
    [submit addTarget:self action:@selector(onBtnFinishedAction:) forControlEvents:UIControlEventTouchUpInside];
    [submit setTitleColor:kColor_W forState:UIControlStateNormal];
    [submit setTitle:@"提交" forState:UIControlStateNormal];
    submit.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    submit.titleLabel.font = kFont_16;
    submit.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
    [self.view addSubview:submit];
    
    [submit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(44+LYSafeAreaBottom());
    }];
    
    aScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight - 44 -LYSafeAreaBottom())];
    aScrollView.delegate = self;
    aScrollView.showsHorizontalScrollIndicator = NO;
    aScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:aScrollView];
    
    [aScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(submit.mas_top);
    }];

    //初始化预约相关参数
    busiTypeId = @"";
    bespeakDate = @"";
    bespeakTimes= @"";
    bespeakEnd = @"";
    //渲染类型和预约控件
    SEGInputTypeView *typeView = [SEGInputTypeView viewFromXIB];
    NSDictionary *data = @{@"title":@"服务分类",
                           @"content":@"请选择服务分类"};
    typeView.dataSource = _inputModel;
    typeView.delegate = self;
    [typeView paddDataWith: data type:SEGEnumsInputTypeView_service];
    typeView.lineView.hidden = YES;
    typeView.tag = 22222;
    [aScrollView addSubview:typeView];
    
    [typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(typeView.superview);
        make.height.mas_equalTo(44);
        make.centerX.equalTo(typeView.superview);
    }];


    //支持预约
    CGFloat nowY = 44+10;
    if ([_inputModel.isBespeak isEqualToString:@"1"]) {
        SEGInputTypeView *breakDateView = [SEGInputTypeView viewFromXIB];
        breakDateView.frame = CGRectMake(0,  nowY, self.view.width, 44);
        breakDateView.delegate = self;
        breakDateView.tag = 33333;
        NSString *dateStr = [[NSDate date] stringNoUTCDateByFormatString:@"yyyy-MM-dd"];
        NSDictionary *data1 = @{@"title":@"选择日期",
                                @"content":dateStr};
        //默认预约时间为当天
        bespeakDate = [[NSDate date] stringNoUTCDateByFormatString:@"yyyy-MM-dd"];
        [breakDateView paddDataWith:data1 type:SEGEnumsInputTypeView_breakDate];
        SEGInputTypeView *breakTimeView = [SEGInputTypeView viewFromXIB];
        breakTimeView.frame = CGRectMake(0, CGRectGetMaxY(breakDateView.frame), self.view.width, 44);
        breakTimeView.delegate = self;
        //默认选择时间段
        NSDictionary *data2 = @{@"title":@"预约时间段",
                                @"content":@"请选择预约时间段",
                                @"dateStr":dateStr
                                };
        [breakTimeView paddDataWith:data2 type:SEGEnumsInputTypeView_breakTime];
        [aScrollView addSubview:breakDateView];
        [aScrollView addSubview:breakTimeView];
        breakTimeView.tag = 11111;
        //有预约功能 去拉取预约时间段数据
        [self loadBespealTimeData];
        nowY += 44+44;
        
        [breakDateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(typeView.superview);
            make.height.mas_equalTo(44);
            make.centerX.equalTo(typeView.superview);
            make.top.equalTo(typeView.mas_bottom).offset(10);
        }];
        
        [breakTimeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(typeView.superview);
            make.height.mas_equalTo(44);
            make.centerX.equalTo(typeView.superview);
            make.top.equalTo(breakDateView.mas_bottom);
        }];
    }

    controlVC = [[ControlTemplateViewController alloc] init];
    controlVC.fundelegate = self;
    controlVC.mastVC = self;
    controlVC.defaultHeight = nowY;
}

#pragma mark - ======================< 生命周期 >========================
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    dataArray = [[NSMutableArray alloc] initWithCapacity:100];
    
    [self loadData];
    //注册键盘弹出通知
    [self registerForKeyboardNotifications];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    NSString* tmp = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"testcase.mp3"];
    
    NSFileManager* fileManager = [[NSFileManager alloc] init];
    if ([fileManager fileExistsAtPath:tmp]) {
        NSLog(@"存在");
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    //停止播放声音
    [[NSNotificationCenter defaultCenter] postNotificationName:@"STOPSOUND" object:nil];
    //[bugfix 28834] 先填写描述再选择房屋，键盘显示不友好
    [self.view endEditing:YES];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag
{
    NSLog(@"played");
}

-(void)loadBespealTimeData
{
    //拉取字典表信息
    [[SEGOrderInputHttpManager sharedManager] getDictListWith:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        //1.失败
        if (isSuccessed == NO) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return ;
        }
        //2.成功
        SEGInputTypeView *breakTimeView = [aScrollView viewWithTag:11111];
        breakTimeView.dataSource =  result[@"data"];
        [breakTimeView configBespealData];
        [breakTimeView refreshUI];
        //刷新显示默认时间段
        [self refreshBespealViewWith:result[@"data"]];
    }];
}

/**
 默认时间段
 */
-(void)refreshBespealViewWith:(NSArray *)dataArray{
    [dataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *endTime = CHECKVALUE(dict[@"bespeakEnd"]);
        if ([self checkIsBespealTimesWith:@{@"bespeakEnd":endTime}]) {
            bespeakEnd = endTime;
            //设置默认值
            SEGInputTypeView *typeView = [aScrollView viewWithTag:11111];
            typeView.contentLabel.text = dict[@"name"];
            bespeakTimes = dict[@"value"];
            typeView.contentLabel.textColor = kColor_1;
            *stop = YES;
        }
    }];
}

/**
 校验时间是否超出范围

 @param dict 需要校验的字典
 @return YES-校验通过 NO-校验不通过
 */
-(BOOL)checkIsBespealTimesWith:(NSDictionary *)dict{
    // 如果没有开始时间就不校验
    if (bespeakDate.length == 0) {
        return YES;
    }
    //结束时间
    NSString *endTime = dict[@"bespeakEnd"];
    //如果结束时间比当前时间早 则不通过
    NSString *selectTime = [SEGUtils getTimeStrWithDate:bespeakDate milliSecond:endTime formatterStr:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *selectDate = [SEGUtils dateFromString:selectTime withFormatString:@"yyyy-MM-dd HH:mm:ss"];
    if ([selectDate isInPast]) {
        return NO;
    }
    return YES;
}

-(void)loadData
{
    dataArray = [[NSMutableArray alloc] init];
    NSDictionary * params = @{@"templateInstId":_inputModel.templateInstId,
                              @"communityId":kAccountCommunityID};
    [SVProgressHUD show];
    [[SEGOrderInputHttpManager sharedManager] getOrderInputDetailDataWith:params type:_type finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        [SVProgressHUD dismiss];
        //1.请求失败
        if (isSuccessed == NO) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return ;
        }
        
        //2.请求成功 - 渲染模板界面
        if (result[@"data"] && [result[@"data"] count] > 0) {
            [dataArray addObjectsFromArray:result[@"data"]];
            [self showDetailView];
        }

    }];
}
#pragma mark - ================<服务类型，预约控件选择回调>===============
/**
 选择值回调
 */
-(void)selectInputTypeCallBack:(NSDictionary *)valueDict type:(SEGEnumsInputTypeView)type
{
    switch (type) {
            //1.选择类型 value = busiTypeId
        case SEGEnumsInputTypeView_service:{
            busiTypeId = valueDict[@"value"];
            busiTypeName = valueDict[@"name"];
            break;
        }
            //2.选择预约日期 value = dateStr
        case SEGEnumsInputTypeView_breakDate:{
            bespeakDate = valueDict[@"value"];
            SEGInputTypeView *breakTimeView = [aScrollView viewWithTag:11111];
            //将日期传给时间段控件
            breakTimeView.tempValue = bespeakDate;
            
            // 判断当前所选时间是否超时 超时重置Time
            if (bespeakEnd && ![self checkIsBespealTimesWith:@{@"bespeakEnd":bespeakEnd}]) {
                bespeakTimes = nil;
                bespeakEnd = nil;
                breakTimeView.contentLabel.text = @"请选择预约时间段";
                breakTimeView.contentLabel.textColor = kColor_C;
            }
            break;
        }
            //3.选择预约时间段 value = codeName
        case SEGEnumsInputTypeView_breakTime:{
            NSString *value = CHECKVALUE(valueDict[@"value"]);
            //校验不通过不赋值
            if (value.length == 0) {
                [SEGAlertView showTmepMessageWithMessage:kTimeErrorToastMessage];
                return;
            }
            bespeakEnd = CHECKVALUE(valueDict[@"bespeakEnd"]);//选择时间段的结束时间 提交时候做校验
            bespeakTimes = value;
            break;
        }
    }
}

#pragma mark - ================<日常 - 工单录入逻辑>===============

-(void)showDetailView
{
    //1.待客录单添加业主信息字段放入到控件里面
    if (_type == SEGOrderInputEnterType_INSTEAD_ORDER_INPUT) {
        [self insetInsteadUesrInfo];
    }
    //2.设备报障需要添加设备编码到设备控件上
    else if (_type == SEGOrderInputEnterType_DEVICE_ORDER_INPUT){
        [self insetDeviceCodeInfo];
    }
    
     [controlVC onCreateTemplateView:dataArray view:aScrollView];
    
}


/**
 加入业主信息到控件里面
 */
-(void)insetInsteadUesrInfo
{
    //先把房屋地址控件的值填充上
    //1.先确定业主信息所在的分组
    __block NSInteger tureGroupId = 0;
    __block NSMutableDictionary *dict_new = [[NSMutableDictionary alloc] init];
    [dataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *group = dict[@"disGroupid"];
        if ( [group integerValue] > tureGroupId) {
            tureGroupId  = [group integerValue];
        }
        
        //将房屋地址控件值填充上
        if ([_userInfo[@"houseName"] length] > 0) {
            if ([dict[@"widgetType"] isEqualToString:@"radiohouse"]) {
                dict_new  = [[NSMutableDictionary alloc] initWithDictionary:dict];
                radioHouseId = dict_new[@"attrInstId"];//记录房屋控件的id
                [dict_new setObject:_userInfo[@"houseName"] forKey:@"attrValue"];
                [dict_new setObject:@"label" forKey:@"widgetType"];
                [dataArray replaceObjectAtIndex:idx withObject:dict_new];
            }
        }
    }];
    
    tureGroupId += 1;
//       titleArray = @[@"姓名", @"手机号", @"地址"];
    //2.确定好分组后，我们直接把用户信息装成lable控件放到数据源里面
    if ([_userInfo[@"custName"] length] > 0) {
        NSDictionary *nameLabel =    @{@"disGroupid":[NSString stringWithFormat:@"%ld",(long)tureGroupId],
                                       @"widgetType":@"label",
                                       @"writable":@"0",
                                       @"readable":@"1",
                                       @"attrValue":_userInfo[@"custName"],
                                       @"title":@"姓名"
                                       };
        [dataArray addObject:nameLabel];
    }
    
    if ([_userInfo[@"custPhone"] length] > 0) {
        NSDictionary *phoneLabel =    @{@"disGroupid":[NSString stringWithFormat:@"%ld",(long)tureGroupId],
                                        @"widgetType":@"label",
                                        @"writable":@"0",
                                        @"readable":@"1",
                                        @"attrValue":_userInfo[@"custPhone"],
                                        @"title":@"手机号"
                                        };
        [dataArray addObject:phoneLabel];
    }
    
    if ([_userInfo[@"houseName"] length] > 0) {
        NSDictionary *phoneLabel =    @{@"disGroupid":[NSString stringWithFormat:@"%ld",(long)tureGroupId],
                                        @"widgetType":@"label",
                                        @"writable":@"0",
                                        @"readable":@"1",
                                        @"attrValue":_userInfo[@"houseName"],
                                        @"title":@"地址"
                                        };
        [dataArray addObject:phoneLabel];
    }
   
    
    
}


/**
 把设备编码插入到设备控件上
 */
-(void)insetDeviceCodeInfo
{
    [dataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
        if ([tempDict[@"widgetType"] isEqualToString:@"equipment"]) {
            if (_equipmentInstCode) {
                [tempDict setObject:_equipmentInstCode forKey:@"attrValue"];
                [dataArray replaceObjectAtIndex:idx withObject:tempDict];
                *stop = YES;
            }
        }
    }];
}


#pragma mark - ======================< 功能方法 >========================
/**
 *  返回按钮，返回时保存填充的数据
 *
 *  @param sender 按钮实例
 */
- (void)onNavigationLeftButtonClicked:(UIButton*)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - ================<提交工单录入表单信息>===============
-(void)onSubmitInputFormAction:(NSDictionary*)tempDict
{
    //防止提交多次
    if (self.isSubmit) {
        return;
    }
    self.isSubmit = YES;
    
    WeakSelf;
    [[SEGHTTPManager sharedNetworkManager] segNetworkStatus:^(SEGNetworkStatus status) {
        BOOL netEnable = (status == SEGNetworkStatusViaWiFi || status == SEGNetworkStatusViaWWAN);
        //无网不提交
        if (!netEnable) {
            [SEGAlertView showTmepMessageWithMessage:kNetworkErrorMessage];
            weakSelf.isSubmit = NO;
            return;
        }
        //检测服务类型，预约是否已填写
        if ([self checkBespealData] == NO) {
            //[SVProgressHUD dismiss];
            [SVProgressHUD dismiss];
            weakSelf.isSubmit = NO;
            return;
        }
        
        //1.先上传图片
        [SVProgressHUD show];
        
        __block NSDictionary *params = [controlVC onReponseTemplateValueWithCheckRequired:YES]; //重新获取所有控件的值
        [controlVC SEGUploadFileControlTemplate:params uploadResult:^(BOOL isSucessed, NSString *message) {
            [SVProgressHUD dismiss];
            
            //图片上传失败
            if (!isSucessed) {
                [SEGAlertView showTmepMessageWithMessage:message];
                self.isSubmit = NO;
                return ;
            }
            //返回所有控件的值，并把值传入params，将params作为参数传入接口（接口会返回一个serviceOrderId）
            params = [controlVC onReponseTemplateValueWithCheckRequired:YES];
            if (![params[@"code"] isEqualToString:@"0"]) {
                self.isSubmit = NO;
                return; //数据校验不成功
            }
            [self submitCommonInputOrderWith:params];
        }];
    }];
}

/**
 普通工单录入提交
 */
-(void)submitCommonInputOrderWith:(NSDictionary *)dict
{
    //1.拼接提交需要的参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    //控件里面含有房屋选择控件，houseId要用选的房屋controlVC.houseId
    NSString *houseId = controlVC.houseId ? controlVC.houseId : [SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.houseId];
    NSString *houseInfo = controlVC.houseInfo ? controlVC.houseInfo : [SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.houseName];

    [params setObject:kAccountUserID forKey:@"userId"]; // 用户id
    [params setObject:[SEGUtils ValueToString:[SEGProfileManager sharedManager].profile.custId] forKey:@"custId"]; //客户id
    [params setObject:kAccountCommunityID forKey:@"communityId"];// 项目id
    [params setObject:houseId.length > 0 ? houseId : @"0" forKey:@"houseId"]; //房屋id
    [params setObject:[SEGProfileManager sharedManager].profile.communityName forKey:@"communityName"];//真实项目名称
    [params setObject:houseInfo.length > 0 ? houseInfo : @"" forKey:@"houseInfo"];//房屋全名
    [params setObject:[SEGProfileManager sharedManager].profile.nickname forKey:@"contactName"];//联系人
    [params setObject:[SEGProfileManager sharedManager].profile.tel forKey:@"contactTel"];//联系人电话

    [params setObject:_inputModel.templateId forKey:@"templateId"];// 模板类型id
    [params setObject:busiTypeId ?: @"" forKey:@"busiTypeId"];// 业务类型id
    [params setObject:_inputModel.templateInstId forKey:@"templateInstId"];// 服务实例id
    [params setObject:dict[@"variables"] forKey:@"variables"];// 控件信息
    if (bespeakDate.length != 0) {
        [params setObject:bespeakDate forKey:@"bespeakDate"];// 预约时间
    }
    if (bespeakTimes.length != 0) {
        [params setObject:bespeakTimes forKey:@"bespeakTimes"];// 预约时间段
    }
   
    if ([self checkIsBespealTimesWith:@{@"bespeakEnd":bespeakEnd}] == NO) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:kTimeErrorToastMessage];
        self.isSubmit = NO;
        return;
    }
    //2.提交表单
    [SVProgressHUD show];
    WeakSelf;
    [[SEGOrderInputHttpManager sharedManager] submitCommonOrderInputDetailDataWith:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:errorMessage];
        //失败
        if (isSuccessed == NO) {
            weakSelf.isSubmit = NO;
            return ;
        }
        //成功
        if (weakSelf.type == SEGOrderInputEnterType_NORMAL_ORDER_INPUT) {//不是待客录单
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SUBMIT_PATROL_DETAIL" object:nil userInfo:result];
            [weakSelf onFinishedAction];
        }
    }];
}


/**
 判断预约是否填写完毕
 */
-(BOOL)checkBespealData
{
    /*
    // 4.9.6需求：7952 不再限制服务子类的必填校验
    if (busiTypeId.length == 0) {
        [SEGAlertView showTmepMessageWithMessage:@"请选择服务类型"];
        return NO;
    }
     */
    
    //有预约功能
    if ([_inputModel.isBespeak isEqualToString:@"1"]) {
        
        if (bespeakDate.length == 0) {
            [SEGAlertView showTmepMessageWithMessage:@"请选择预约日期"];
            return NO;
        }
    if (bespeakTimes.length == 0) {
        [SEGAlertView showTmepMessageWithMessage:@"请选择预约时间段"];
        return NO;
    }
  }
    return YES;
}



/**
 *  提交数据
 */
- (void)onBtnFinishedAction:(UIButton*)sender
{
    NSDictionary* tempDict = [controlVC onReponseTemplateValueWithCheckRequired:YES];
    if ([[tempDict valueForKey:@"code"] isEqualToString:@"0"]) {
        
        [self onSubmitInputFormAction:tempDict];
    }
    else{
         [SVProgressHUD dismiss];
    }
}



/**
 *  返回上一层并删除所填写的值
 */
- (void)onFinishedAction
{
    //录单完成通知待办列表刷新数据
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.navigationController popViewControllerAnimated:YES];
//    });
    
    // [bugfix 28833]偶现提交工单成功停留在当前页面，没有返回h上一页
    // 没有复现 先去掉延迟逻辑
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
    nowY = scrollView.contentOffset.y;
}


#pragma mark - ======================< 键盘弹出 >========================

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification*)notif
{
    NSDictionary* info = [notif userInfo];
    
    UIView* textView = [info objectForKey:@"object"];
    CGRect parentRect = [textView convertRect:textView.bounds toView:aScrollView];
    
    
    if ([[UIScreen mainScreen] bounds].size.height == 480) {
        if (parentRect.origin.y > 100) {
            [aScrollView setContentOffset:CGPointMake(0, parentRect.origin.y) animated:YES];
        }
    }
    else {
        if (parentRect.origin.y > 100) {
            [aScrollView setContentOffset:CGPointMake(0, parentRect.origin.y - 100) animated:YES];
        }
    }
    
}
- (void)keyboardWasHidden:(NSNotification*)notif
{
    NSDictionary* info = [notif userInfo];
    
    UIView* textView = [info objectForKey:@"object"];
    CGRect parentRect = [textView convertRect:textView.bounds toView:aScrollView];
    
    if ([[UIScreen mainScreen] bounds].size.height == 480) {
        if (parentRect.origin.y > 100) {
            if (aScrollView.contentSize.height <= 480) {
                [aScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            else {
                [aScrollView setContentOffset:CGPointMake(0, nowY) animated:YES];
            }
        }
    }
    else {
        if (parentRect.origin.y > 100) {
            
            if (nowY > 100) {
                
                if (aScrollView.contentSize.height > LYScreenHeight() - kNavigationBarAndStatusBarHeight)
                {
                    [aScrollView setContentOffset:CGPointMake(0, nowY -100) animated:YES];
                }
                else
                {
                    [aScrollView setContentOffset:CGPointMake(0, nowY -(parentRect.origin.y-100)) animated:YES];
                }
                
            }
            else {
                [aScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            
        }
    }
}

#pragma mark - getter

@end
